/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import model.Mahasiswa;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author shofyan
 */
public class MahasiswaDao {

    SessionFactory sessFact = HibernateUtil.getSessionFactory();

    public boolean insertMahasiswa(Mahasiswa mhs) {
        try {

            Session sess = sessFact.getCurrentSession();
            Transaction tr = sess.beginTransaction();
            sess.save(mhs);
            tr.commit();
            System.out.println("Successfully inserted");
            sessFact.close();
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    public boolean UpdateMahasiswa(Mahasiswa mhs){
         try {

            Session sess = sessFact.getCurrentSession();
            Transaction tr = sess.beginTransaction();
            
            Mahasiswa st = (Mahasiswa)sess.load(Mahasiswa.class,mhs.getNIM());
            st = mhs;
            tr.commit();
            System.out.println("Successfully Update");
            sessFact.close();
            return true;
        } catch (Exception e) {
            return false;
        }
        
        
    }
    public List<Mahasiswa> getAll() {
        List<Mahasiswa> mahasiswas = new ArrayList();
        try {
            Session sess = sessFact.getCurrentSession();
            Transaction tr = sess.beginTransaction();
            Query query = sess.createQuery("from Mahasiswa");
            List result = query.list();
            Iterator it = result.iterator();
            System.out.println("id  sname  sroll  scourse");


            while (it.hasNext()) {
                Mahasiswa st = (Mahasiswa) it.next();
                Mahasiswa mhs = new Mahasiswa();
                mhs.setNIM(st.getNIM());
                mhs.setName(st.getName());
                mhs.setTanggalLahir(st.getTanggalLahir());
                mhs.setJurusan(st.getJurusan());
                mhs.setAlamat(st.getAlamat());
                mahasiswas.add(mhs);
            }
            sessFact.close();
            return mahasiswas;

        } catch (Exception e) {
            System.out.println("gagal bro" + e);
        }
        return mahasiswas;

    }
}
